package com.zhang.service.redis;

import com.zhang.dao.UserCount;
import com.zhang.dao.WordCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RedisServiceImpl implements RedisServiceInter{
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    @Qualifier("yyyyMMdd")
    SimpleDateFormat yyyyMMdd;

    @Value("${msg.prefix}")
    String msgPrefix;

    @Value("${user.prefix}")
    String userPrefix;


    @Override
    public void sendUserMassage(String msg) {
        redisTemplate.opsForValue().increment(msgPrefix + ":" + msg, 1);
    }

    @Override
    public void sendUserName(String name) {
        redisTemplate.opsForValue().increment(userPrefix + ":" + name, 1);
    }

    @Override
    public List<WordCount> getWordByCount(int count) {
        Set<String> keys = redisTemplate.keys(msgPrefix + ":*");

        ArrayList<WordCount> wordList = new ArrayList<>();

        for (String key : keys) {
            WordCount tempWord = new WordCount(key.substring(4), Long.parseLong(redisTemplate.opsForValue().get(key)));
            wordList.add(tempWord);
        }

        List<WordCount> res = wordList.stream()
                .sorted((w1, w2) -> (int) (w2.getCount() - w1.getCount()))
                .collect(Collectors.toList());

        if(count >= res.size()){
            return res;
        }
        return res.subList(0, count);
    }

    @Override
    public List<UserCount> getUserByCount(int count) {
        Set<String> keys = redisTemplate.keys(userPrefix + ":*");

        ArrayList<UserCount> wordList = new ArrayList<>();

        for (String key : keys) {
            UserCount tempWord = new UserCount(key.substring(5), Integer.parseInt(redisTemplate.opsForValue().get(key)));
            wordList.add(tempWord);
        }

        List<UserCount> res = wordList.stream()
                .sorted((w1, w2) -> w2.getCount() - w1.getCount())
                .collect(Collectors.toList());

        if(count >= res.size()){
            return res;
        }
        return res.subList(0, count);
    }
}
